import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../core/constants.dart';
import '../../shared/models/wrong_question.dart';
import '../../shared/models/word.dart';
import '../../shared/providers/word_provider.dart';
import '../../shared/providers/vocabulary_learning_provider.dart';
import '../../shared/services/storage_service.dart';
import '../../data/master_vocabulary.dart';
import '../words/favorites_page.dart';

final wrongQuestionsProvider = FutureProvider<List<WrongQuestion>>((ref) async {
  final storageService = ref.watch(storageServiceProvider);
  // 监听刷新触发器，确保在答题后能同步更新
  ref.watch(refreshTriggerProvider);
  final wrongQuestions = await storageService.getWrongQuestions();
  // 按时间倒序排列，最新的错题在前面
  wrongQuestions.sort((a, b) => b.wrongAt.compareTo(a.wrongAt));
  return wrongQuestions;
});

class WrongQuestionsPage extends ConsumerStatefulWidget {
  const WrongQuestionsPage({super.key});

  @override
  ConsumerState<WrongQuestionsPage> createState() => _WrongQuestionsPageState();
}

class _WrongQuestionsPageState extends ConsumerState<WrongQuestionsPage>
    with TickerProviderStateMixin {
  bool _isPracticeMode = false;
  List<WrongQuestion> _practiceQuestions = [];
  int _currentQuestionIndex = 0;
  int _totalCorrect = 0;
  int _totalAnswered = 0;
  List<bool> _answersCorrectness = []; // 记录每题的答题正确性
  
  // 动画控制器 - 完全和单词学习页面一样
  late AnimationController _cardAnimationController;
  late AnimationController _progressAnimationController;
  late Animation<double> _cardAnimation;
  late Animation<double> _progressAnimation;
  

  
  Timer? _autoNextTimer;
  int? _selectedAnswer;
  bool _showResult = false;

  @override
  void initState() {
    super.initState();
    
    // 初始化动画控制器 - 和单词学习页面完全一样
    _cardAnimationController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    
    _progressAnimationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _cardAnimation = CurvedAnimation(
      parent: _cardAnimationController,
      curve: Curves.easeInOutBack,
    );
    
    _progressAnimation = CurvedAnimation(
      parent: _progressAnimationController,
      curve: Curves.easeOutCubic,
    );
    

  }

  @override
  void dispose() {
    _cardAnimationController.dispose();
    _progressAnimationController.dispose();
    _autoNextTimer?.cancel();
    super.dispose();
  }



  void _startPractice() async {
    final wrongQuestionsAsync = ref.read(wrongQuestionsProvider);
    final wrongQuestions = wrongQuestionsAsync.value;
    if (wrongQuestions == null || wrongQuestions.isEmpty) return;

    setState(() {
      _isPracticeMode = true;
      _practiceQuestions = List.from(wrongQuestions);
      _currentQuestionIndex = 0;
      _totalCorrect = 0;
      _totalAnswered = 0;
      _answersCorrectness = List.filled(wrongQuestions.length, false);
      _selectedAnswer = null;
      _showResult = false;
    });
    
    // 启动动画
    _cardAnimationController.forward();
    _progressAnimationController.forward();
  }

  void _onAnswerSelected(int index) {
    if (_selectedAnswer != null) return;

    setState(() {
      _selectedAnswer = index;
      _showResult = true;
      _totalAnswered++;
    });

    final currentQuestion = _practiceQuestions[_currentQuestionIndex];
    final isCorrect = index == currentQuestion.correctIndex;
    
    if (isCorrect) {
      _totalCorrect++;
    }
    
    // 记录当前题目的答题正确性
    _answersCorrectness[_currentQuestionIndex] = isCorrect;

    // 1.5秒后自动跳转下一题 - 和单词学习页面一样
    _autoNextTimer = Timer(const Duration(milliseconds: 1500), () {
      _nextQuestion();
    });
  }

  void _nextQuestion() {
    _autoNextTimer?.cancel();
    
    if (_currentQuestionIndex < _practiceQuestions.length - 1) {
      _cardAnimationController.reverse().then((_) {
        setState(() {
          _currentQuestionIndex++;
          _selectedAnswer = null;
          _showResult = false;
        });
        _cardAnimationController.forward();
        _progressAnimationController.forward();
      });
    } else {
      // 练习完成
      _completePractice();
    }
  }

  void _completePractice() async {
    // 移除答对的题目
    for (int i = 0; i < _practiceQuestions.length; i++) {
      if (_answersCorrectness[i]) { // 如果这道题答对了
        await ref.read(storageServiceProvider).removeWrongQuestion(_practiceQuestions[i].wordId);
      }
    }

    // 刷新错题本数据
    ref.invalidate(wrongQuestionsProvider);
    ref.read(refreshTriggerProvider.notifier).state++;
  }

  void _restartPractice() {
    setState(() {
      _currentQuestionIndex = 0;
      _totalCorrect = 0;
      _totalAnswered = 0;
      _answersCorrectness = List.filled(_practiceQuestions.length, false);
      _selectedAnswer = null;
      _showResult = false;
    });
    _cardAnimationController.forward();
    _progressAnimationController.reset();
    _progressAnimationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    final wrongQuestions = ref.watch(wrongQuestionsProvider);
    final favoriteWords = ref.watch(favoriteWordsProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text(_isPracticeMode ? 'Wrong Questions Practice' : 'Wrong Questions'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.red.shade600,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.red.shade600,
                Colors.red.shade800,
              ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () {
              if (_isPracticeMode) {
                setState(() {
                  _isPracticeMode = false;
                });
              } else {
                Navigator.pop(context);
              }
            },
          ),
        ),
        actions: _isPracticeMode && _practiceQuestions.isNotEmpty ? [
          if (_practiceQuestions.isNotEmpty && _currentQuestionIndex < _practiceQuestions.length)
            Container(
              margin: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Stack(
                children: [
                  IconButton(
                    onPressed: () {
                      ref.read(favoriteWordsProvider.notifier)
                          .toggleFavorite(_practiceQuestions[_currentQuestionIndex].wordId);
                      ref.read(starredRefreshProvider.notifier).state++;
                    },
                    icon: FaIcon(
                      favoriteWords.contains(_practiceQuestions[_currentQuestionIndex].wordId)
                          ? FontAwesomeIcons.solidStar
                          : FontAwesomeIcons.star,
                      color: favoriteWords.contains(_practiceQuestions[_currentQuestionIndex].wordId)
                          ? Colors.amber
                          : Colors.white70,
                      size: 18,
                    ),
                  ),
                ],
              ),
            ),
        ] : null,
      ),
      body: _isPracticeMode 
          ? _buildPracticeMode() 
          : wrongQuestions.when(
              data: (data) => _buildBrowseMode(data),
              loading: () => const Center(child: CircularProgressIndicator()),
              error: (error, stack) => Center(
                child: Text('Error: $error'),
              ),
            ),
    );
  }

  Widget _buildPracticeMode() {
    if (_practiceQuestions.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_currentQuestionIndex >= _practiceQuestions.length) {
      return _buildCompletionScreen();
    }

    return _buildLearningContent();
  }

  Widget _buildLearningContent() {
    final question = _practiceQuestions[_currentQuestionIndex];

    return Column(
      children: [
        _buildProgressBar(),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              children: [
                _buildQuestionCard(question),
                const SizedBox(height: 40),
                _buildOptionsGrid(question),
                const SizedBox(height: 20),
                _buildBottomInfo(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildProgressBar() {
    final progress = _practiceQuestions.isEmpty ? 0.0 : 
        (_currentQuestionIndex + 1) / _practiceQuestions.length;
    final accuracy = _totalAnswered == 0 ? 0.0 : _totalCorrect / _totalAnswered;
    
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '${_currentQuestionIndex + 1} / ${_practiceQuestions.length}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppConstants.DARK_BLUE,
                ),
              ),
              Text(
                'Accuracy: ${(accuracy * 100).toInt()}%',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppConstants.PRIMARY_BLUE,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          AnimatedBuilder(
            animation: _progressAnimation,
            builder: (context, child) {
              return LinearProgressIndicator(
                value: progress * _progressAnimation.value,
                backgroundColor: Colors.grey[300],
                valueColor: AlwaysStoppedAnimation<Color>(Colors.red.shade600),
                minHeight: 6,
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionCard(WrongQuestion question) {
    // 从wordId获取单词信息
    final word = MasterVocabulary.allVocabulary.firstWhere(
      (w) => w.id == question.wordId,
      orElse: () => Word(
        id: question.wordId,
        esperanto: 'Unknown',
        english: 'Unknown',
        definition: 'Unknown word',
        pronunciation: '',
        examples: [],
        category: 'Unknown',
        difficulty: 1,
        audioUrl: '',
      ),
    );
    
    return AnimatedBuilder(
      animation: _cardAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _cardAnimation.value,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.all(30),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.red.shade600.withOpacity(0.9),
                  Colors.red.shade800,
                ],
              ),
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.red.shade600.withOpacity(0.3),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              children: [
                const FaIcon(
                  FontAwesomeIcons.triangleExclamation,
                  color: Colors.white,
                  size: 32,
                ),
                const SizedBox(height: 20),
                Text(
                  word.esperanto,
                  style: const TextStyle(
                    fontSize: 36,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    letterSpacing: 1.2,
                  ),
                ),
                const SizedBox(height: 12),
                if (word.pronunciation.isNotEmpty)
                  Text(
                    '[${word.pronunciation}]',
                    style: const TextStyle(
                      fontSize: 18,
                      color: Colors.white70,
                      fontStyle: FontStyle.italic,
                    ),
                  ),
                const SizedBox(height: 20),
                const Text(
                  'Choose the correct English translation:',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildOptionsGrid(WrongQuestion question) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 2.5,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
      ),
      itemCount: question.options.length,
      itemBuilder: (context, index) {
        return _buildOptionButton(question, index);
      },
    );
  }

  Widget _buildOptionButton(WrongQuestion question, int index) {
    final option = question.options[index];
    final isSelected = _selectedAnswer == index;
    final isCorrect = index == question.correctIndex;
    
    Color backgroundColor = Colors.white;
    Color borderColor = Colors.grey.withOpacity(0.3);
    Color textColor = AppConstants.DARK_BLUE;
    
    if (_showResult && isSelected) {
      if (isCorrect) {
        backgroundColor = Colors.green.withOpacity(0.1);
        borderColor = Colors.green;
        textColor = Colors.green.shade700;
      } else {
        backgroundColor = Colors.red.withOpacity(0.1);
        borderColor = Colors.red;
        textColor = Colors.red.shade700;
      }
    } else if (_showResult && isCorrect) {
      backgroundColor = Colors.green.withOpacity(0.1);
      borderColor = Colors.green;
      textColor = Colors.green.shade700;
    }

    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      child: Material(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(16),
        child: InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: _selectedAnswer == null ? () => _onAnswerSelected(index) : null,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: borderColor, width: 2),
            ),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  if (_showResult && isSelected) ...[
                    FaIcon(
                      isCorrect ? FontAwesomeIcons.check : FontAwesomeIcons.xmark,
                      color: isCorrect ? Colors.green : Colors.red,
                      size: 16,
                    ),
                    const SizedBox(width: 8),
                  ],
                  Flexible(
                    child: Text(
                      option,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: textColor,
                      ),
                      textAlign: TextAlign.center,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
            icon: FontAwesomeIcons.bullseye,
            label: 'Correct',
            value: '$_totalCorrect',
            color: Colors.green,
          ),
          _buildStatItem(
            icon: FontAwesomeIcons.triangleExclamation,
            label: 'Wrong Questions',
            value: '${_practiceQuestions.length}',
            color: Colors.red.shade600,
          ),
          _buildStatItem(
            icon: FontAwesomeIcons.chartLine,
            label: 'Progress',
            value: '${(((_currentQuestionIndex + 1) / _practiceQuestions.length) * 100).toInt()}%',
            color: AppConstants.PRIMARY_BLUE,
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Column(
      children: [
        FaIcon(icon, color: color, size: 20),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildCompletionScreen() {
    final accuracy = _totalAnswered == 0 ? 0.0 : _totalCorrect / _totalAnswered;
    final isGoodScore = accuracy >= 0.7;
    
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: isGoodScore 
                      ? [Colors.green.shade600, Colors.green.shade800]
                      : [Colors.orange.shade600, Colors.orange.shade800],
                ),
                shape: BoxShape.circle,
              ),
              child: Center(
                child: FaIcon(
                  isGoodScore ? FontAwesomeIcons.trophy : FontAwesomeIcons.thumbsUp,
                  color: Colors.white,
                  size: 50,
                ),
              ),
            ),
            const SizedBox(height: 32),
            Text(
              isGoodScore ? 'Excellent Work!' : 'Good Effort!',
              style: const TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.bold,
                color: AppConstants.DARK_BLUE,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              isGoodScore 
                  ? 'You\'ve mastered these wrong questions!'
                  : 'Keep practicing to improve your accuracy!',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey[600],
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            _buildResultStats(),
            const SizedBox(height: 32),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _restartPractice,
                    icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 16),
                    label: const Text('Practice Again'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red.shade600,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () {
                      setState(() {
                        _isPracticeMode = false;
                      });
                    },
                    icon: const FaIcon(FontAwesomeIcons.list, size: 16),
                    label: const Text('View List'),
                    style: OutlinedButton.styleFrom(
                      foregroundColor: Colors.red.shade600,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildResultStats() {
    final accuracy = _totalAnswered == 0 ? 0.0 : _totalCorrect / _totalAnswered;
    
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Column(
                children: [
                  Text(
                    '$_totalCorrect',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.green,
                    ),
                  ),
                  const Text(
                    'Correct',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
              Column(
                children: [
                  Text(
                    '${_totalAnswered - _totalCorrect}',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.red,
                    ),
                  ),
                  const Text(
                    'Wrong',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
              Column(
                children: [
                  Text(
                    '${(accuracy * 100).toInt()}%',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: AppConstants.PRIMARY_BLUE,
                    ),
                  ),
                  const Text(
                    'Accuracy',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildBrowseMode(List<WrongQuestion> wrongQuestions) {
    if (wrongQuestions.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.check_circle_outline,
              size: 80,
              color: Colors.green,
            ),
            SizedBox(height: 16),
            Text(
              'No wrong questions yet!',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.green,
              ),
            ),
            SizedBox(height: 8),
            Text(
              'Keep learning to build your vocabulary',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    return Column(
      children: [
        // 统计信息卡片
        Container(
          margin: const EdgeInsets.all(16),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.red.shade50,
                Colors.red.shade100,
              ],
            ),
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.red.withOpacity(0.1),
                spreadRadius: 1,
                blurRadius: 5,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildBrowseStatItem('Total Wrong', wrongQuestions.length.toString(), Icons.error_outline),
                  _buildBrowseStatItem('Most Attempts', _getMostAttempts(wrongQuestions).toString(), Icons.repeat),
                  _buildBrowseStatItem('Recent', _getRecentCount(wrongQuestions).toString(), Icons.schedule),
                ],
              ),
              const SizedBox(height: 16),
              // 开始练习按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: _startPractice,
                  icon: const Icon(Icons.play_arrow),
                  label: const Text('Start Practice'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        // 错题列表
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: wrongQuestions.length,
            itemBuilder: (context, index) {
              final wrongQuestion = wrongQuestions[index];
              return _buildWrongQuestionCard(wrongQuestion);
            },
          ),
        ),
      ],
    );
  }

  Widget _buildBrowseStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.red, size: 24),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.red,
          ),
        ),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  Widget _buildWrongQuestionCard(WrongQuestion wrongQuestion) {
    // 获取对应的单词信息
    final word = MasterVocabulary.allVocabulary.firstWhere(
      (w) => w.id == wrongQuestion.wordId,
      orElse: () => Word(
        id: wrongQuestion.wordId,
        esperanto: 'Unknown',
        english: 'Unknown',
        definition: 'Unknown word',
        pronunciation: '',
        examples: [],
        category: 'Unknown',
        difficulty: 1,
        audioUrl: '',
      ),
    );

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ExpansionTile(
        leading: Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: Colors.red.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: const Icon(
            Icons.error_outline,
            color: Colors.red,
          ),
        ),
        title: Text(
          word.esperanto,
          style: const TextStyle(
            fontWeight: FontWeight.w600,
            color: AppConstants.DARK_BLUE,
          ),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Correct: ${word.english}',
              style: const TextStyle(
                fontSize: 14,
                color: Colors.green,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                const Icon(Icons.repeat, size: 14, color: Colors.grey),
                const SizedBox(width: 4),
                Text(
                  '${wrongQuestion.attemptCount} attempts',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(width: 16),
                const Icon(Icons.schedule, size: 14, color: Colors.grey),
                const SizedBox(width: 4),
                Text(
                  _formatDateTime(wrongQuestion.wrongAt),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ],
        ),
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  wrongQuestion.question,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 12),
                ...wrongQuestion.options.asMap().entries.map<Widget>((entry) {
                  final index = entry.key;
                  final option = entry.value;
                  final isCorrect = index == wrongQuestion.correctIndex;
                  final isSelected = index == wrongQuestion.selectedIndex;
                  
                  return Container(
                    margin: const EdgeInsets.only(bottom: 8),
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: isCorrect 
                          ? Colors.green.withOpacity(0.1)
                          : isSelected 
                              ? Colors.red.withOpacity(0.1)
                              : Colors.grey.withOpacity(0.05),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: isCorrect 
                            ? Colors.green
                            : isSelected 
                                ? Colors.red
                                : Colors.grey.withOpacity(0.3),
                        width: isCorrect || isSelected ? 2 : 1,
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          isCorrect 
                              ? Icons.check_circle
                              : isSelected 
                                  ? Icons.cancel
                                  : Icons.radio_button_unchecked,
                          color: isCorrect 
                              ? Colors.green
                              : isSelected 
                                  ? Colors.red
                                  : Colors.grey,
                          size: 20,
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            option,
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: isCorrect || isSelected ? FontWeight.w500 : FontWeight.normal,
                              color: isCorrect 
                                  ? Colors.green.shade700
                                  : isSelected 
                                      ? Colors.red.shade700
                                      : Colors.black87,
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                }),
                const SizedBox(height: 12),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton.icon(
                      onPressed: () => _removeWrongQuestion(wrongQuestion.wordId),
                      icon: const Icon(Icons.check, size: 18),
                      label: const Text('Mark as Learned'),
                      style: TextButton.styleFrom(
                        foregroundColor: Colors.green,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);
    
    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'Just now';
    }
  }

  void _removeWrongQuestion(String wordId) async {
    final storageService = ref.read(storageServiceProvider);
    await storageService.removeWrongQuestion(wordId);
    ref.invalidate(wrongQuestionsProvider);
  }

  int _getMostAttempts(List<WrongQuestion> wrongQuestions) {
    if (wrongQuestions.isEmpty) return 0;
    return wrongQuestions.map((q) => q.attemptCount).reduce((a, b) => a > b ? a : b);
  }

  int _getRecentCount(List<WrongQuestion> wrongQuestions) {
    final now = DateTime.now();
    final yesterday = now.subtract(const Duration(days: 1));
    return wrongQuestions.where((q) => q.wrongAt.isAfter(yesterday)).length;
  }
} 